import { deviceDetection } from "@pureadmin/utils";
import dayjs from "dayjs";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import userAvatar from "@/assets/user.jpg";
import ReCropperPreview from "@/components/ReCropperPreview";
import { h, reactive, ref, onMounted, computed } from "vue";
import { useDark } from "@pureadmin/utils";
import { uploadBase64 } from "@/api/common";
import {
  getCurrentOperationLogs,
  getUserInfo,
  updateUser,
  updateAvatar
} from "@/api/system";

export function useProfile() {
  const form = reactive({
    id: 0,
    userName: "",
    mobile: "",
    email: "",
    nickName: "",
    avatar: "",
    password: ""
  });
  const avatarInfo = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const isShowAvatarEdit = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 当前网页是否为`dark`模式 请求方法style
  const { isDark } = useDark();
  const methodStyle = computed(() => {
    return (action: string) => {
      let style = {};
      switch (action) {
        case "POST":
          style = {
            "--el-tag-text-color": isDark.value ? "#6abe39" : "#389e0d",
            "--el-tag-bg-color": isDark.value ? "#172412" : "#f6ffed",
            "--el-tag-border-color": isDark.value ? "#274a17" : "#b7eb8f"
          };
          break;
        case "GET":
          style = {
            "--el-tag-text-color": isDark.value ? "#e84749" : "#cf1322",
            "--el-tag-bg-color": isDark.value ? "#2b1316" : "#fff1f0",
            "--el-tag-border-color": isDark.value ? "#58191c" : "#ffa39e"
          };
          break;
        case "PUT":
          style = {
            "--el-tag-text-color": isDark.value ? "#f9c700" : "#fadb14",
            "--el-tag-bg-color": isDark.value ? "#3b3b3b" : "#fffbe6",
            "--el-tag-border-color": isDark.value ? "#595959" : "#ffe58f"
          };
          break;
        case "DELETE":
          style = {
            "--el-tag-text-color": isDark.value ? "#096dd9" : "#096dd9",
            "--el-tag-bg-color": isDark.value ? "#122b40" : "#e6f7ff",
            "--el-tag-border-color": isDark.value ? "#1d39c4" : "#91d5ff"
          };
          break;
        default:
          style = {
            "--el-tag-text-color": isDark.value ? "#6abe39" : "#389e0d",
            "--el-tag-bg-color": isDark.value ? "#172412" : "#f6ffed",
            "--el-tag-border-color": isDark.value ? "#274a17" : "#b7eb8f"
          };
      }
      return style;
    };
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "请求方法",
      prop: "action",
      minWidth: 140,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={methodStyle.value(row.action)}>
          {row.action}
        </el-tag>
      )
    },
    {
      label: "操作标识",
      prop: "auth",
      minWidth: 140
    },
    {
      label: "操作 IP",
      prop: "ip_address",
      minWidth: 100
    },
    {
      label: "路径",
      prop: "path",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "os",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "browser",
      minWidth: 100
    },
    {
      label: "操作时间",
      prop: "createtime",
      minWidth: 180,
      formatter: ({ createtime }) =>
        dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")
    }
  ];

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    // tableRef.value.setAdaptive();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const filter = [];
    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "desc"
    };
    const { data } = await getCurrentOperationLogs(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    loading.value = false;
  }

  async function getCurrentUserInfo() {
    const userInfo = (await getUserInfo()) as { data: Record<string, any> };
    form.userName = userInfo.data?.userName ?? "";
    form.mobile = userInfo.data?.mobile ?? "";
    form.email = userInfo.data?.email ?? "";
    form.nickName = userInfo.data?.nickName ?? "";
    form.avatar = userInfo.data?.avatar ?? "";
    form.id = userInfo.data?.id ?? 0;
  }

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: row.avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        console.log("裁剪后的图片信息：", avatarInfo.value);
        if (row.id == 0) return;
        uploadBase64({ base64str: avatarInfo.value.base64 }).then(res => {
          console.log("uploadBase64", res);
          if (res.code && res.data.full_path) {
            updateAvatar({ id: row.id, avatar: res.data.full_path }).then(
              res => {
                done(); // 关闭弹框
                if (res.code) {
                  message("上传头像成功", { type: "success" });
                  getCurrentUserInfo(); // 刷新表格数据
                } else {
                  message("上传头像失败", { type: "error" });
                }
              }
            );
          } else {
            done(); // 关闭弹框
          }
        });
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  async function onSubmite() {
    updateUser(form).then(res => {
      if (res.code) {
        form.password = "";
        message("Update success!", {
          type: "success"
        });
      } else {
        message(res.msg, {
          type: "error"
        });
      }
    });
  }
  const resetForm = formEl => {
    if (!formEl) return;
    getCurrentUserInfo();
  };
  onMounted(() => {
    onSearch();
    getCurrentUserInfo();
  });

  return {
    form,
    isShowAvatarEdit,
    pagination,
    dataList,
    loading,
    columns,
    handleUpload,
    onSearch,
    onSubmite,
    resetForm,
    deviceDetection,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange
  };
}
